package com.quectel.util.mybatis;

import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;

/**
 * mybatis plus帮助类
 *
 * @author: caolu
 * @email: louis.cao@quectel.com
 * @date: 2022-12-07 14:05:00
 */
public class MyBatisPlusUtils {

    /**
     * 无差别更新所有列
     *
     * @param entity
     * @param mapper
     * @param <T>
     * @return
     */
    public static <T> int updateAllColumnById(T entity, BaseMapper<T> mapper) {
        TableInfo tableInfo = TableInfoHelper.getTableInfo(entity.getClass());
        UpdateWrapper<T> updateWrapper = new UpdateWrapper<>();
        for (TableFieldInfo tableFieldInfo : tableInfo.getFieldList()) {
            updateWrapper.set(tableFieldInfo.getColumn(), ReflectUtil.getFieldValue(entity, tableFieldInfo.getProperty()));
        }
        updateWrapper.eq(tableInfo.getKeyColumn(), ReflectUtil.getFieldValue(entity, tableInfo.getKeyProperty()));
        return mapper.update(entity, updateWrapper);
    }
}
